package com.dxx.cloud.admin.service.wx.impl;

import com.dxx.cloud.admin.module.request.PayRequest;
import com.dxx.cloud.admin.module.response.UnifiedOrderResponse;
import com.dxx.cloud.admin.module.response.wx.CreateOrderResponse;
import com.dxx.cloud.admin.service.wx.IDxxWxPayService;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;

/**
 * @author 37048
 */
@Service
public class DxxWxPayServiceImpl implements IDxxWxPayService {

    @Resource
    private WxPayService wxPayService;



    @Override
    public UnifiedOrderResponse unifiedOrder(PayRequest payRequest) throws WxPayException {

        CreateOrderResponse orderV3 = wxRequestPayment(payRequest);
        UnifiedOrderResponse unifiedOrderResponse = new UnifiedOrderResponse();
        return unifiedOrderResponse;
    }

    @Override
    public CreateOrderResponse wxRequestPayment(PayRequest payRequest) throws WxPayException {
        String outTradeNo = System.currentTimeMillis()+"" +RandomUtils.secure().randomInt(100000,999999);
        WxPayUnifiedOrderV3Request request = new WxPayUnifiedOrderV3Request();
        request
                .setAmount(new WxPayUnifiedOrderV3Request.Amount().setTotal(BaseWxPayRequest.yuan2Fen(payRequest.getFee())).setCurrency("CNY"))
                .setOutTradeNo(System.currentTimeMillis()+"" +RandomUtils.secure().randomInt(100000,999999))
//                .setTimeExpire()
                .setDescription("dxx")
                .setPayer(new WxPayUnifiedOrderV3Request.Payer().setOpenid(payRequest.getOpenId()))
                .setGoodsTag("dxx")
                .setNotifyUrl("http://81.68.69.48:9011/wx/notice")
        ;
        CreateOrderResponse response = new CreateOrderResponse();
        response.setPrepayid(outTradeNo);
        response.setPartnerid(wxPayService.getConfig().getMchId());
        WxPayUnifiedOrderV3Result.JsapiResult result = wxPayService.createOrderV3(TradeTypeEnum.JSAPI, request);
        response.setAppid(wxPayService.getConfig().getAppId());
        response.setNoncestr(result.getNonceStr());
        response.setPackageStr(result.getPackageValue());
        response.setTimestamp(result.getTimeStamp());
        response.setSign(result.getPaySign());
        response.setSignType(result.getSignType());
        return response;
    }
}
